// pages/register/register-collector.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    progressWidth: 0,
    cameraCtx: undefined,
    cameraListener: undefined,
    takingPicture: false,
    
    // rectangleCanvas: undefined,
    // rectangleCanvasCtx: undefined,
    rectangleCanvasWidth: undefined,
    rectangleCanvasHeight: undefined,
    
    screenShotCanvas: undefined,
    screenShotCanvasCtx: undefined,

    tipDisplay: 'none',
    hide: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.updateProgressWidth()
    // const appInstance = getApp()
    // const blazeFaceModel = appInstance.globalData.blazeFaceModel
    this.data.cameraCtx = wx.createCameraContext()
    // let count = 0;
    // this.data.cameraListener = this.data.cameraCtx.onCameraFrame((frame) => {
    //   if (this.data.takingPicture) {
    //     console.log(frame)
    //     this.storePhoto(frame, blazeFaceModel)
    //     this.setData({takingPicture: false})
    //   }
    // })
    // this.data.cameraListener.start()
    // this.data.photos = wx.getStorageSync('photos') || []

    const query = wx.createSelectorQuery()
    query.select('#rectangleCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        // console.log(res)
        const width = res[0].width
        const height = res[0].height
        this.setData({rectangleCanvasWidth: width})
        this.setData({rectangleCanvasHeight: height})
        // console.log(width, height)
        const rectangleCanvas = res[0].node
        const rectangleCanvasCtx = rectangleCanvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        rectangleCanvas.width = width * dpr
        rectangleCanvas.height = height * dpr
        rectangleCanvasCtx.scale(dpr, dpr)
        rectangleCanvasCtx.beginPath()
        rectangleCanvasCtx.lineWidth = '4'
        rectangleCanvasCtx.strokeStyle = 'rgba(255, 255, 255, 0.5)'
        rectangleCanvasCtx.rect((width - 350) / 2, 80, 350, 350)
        rectangleCanvasCtx.stroke()
      })
    query.select('#screenShotCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const width = res[1].width
        const height = res[1].height
        // console.log(width, height)
        this.data.screenShotCanvas = res[1].node
        this.data.screenShotCanvasCtx = this.data.screenShotCanvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        this.data.screenShotCanvas.width = width * dpr
        this.data.screenShotCanvas.height = height * dpr
        this.data.screenShotCanvasCtx.scale(dpr, dpr)
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.data.listener.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  back: function() {
    wx.navigateBack({ delta: 1})    
  },
  takePhoto: function () {
    if (this.data.progressWidth < 100) {
      this.data.cameraCtx.takePhoto({
        quality: 'high',
        success: (res) => {
          console.log(res.tempImagePath)
          const collectorImage = this.data.screenShotCanvas.createImage()
          collectorImage.onload = () => {
            this.data.screenShotCanvasCtx.drawImage(collectorImage, (this.data.rectangleCanvasWidth - 350) / 2, 80, 350, 350, 0, 0, 350, 350 )
            // console.log(this.data.screenShotCanvas.toDataURL('image/webp'))
            this.storePhoto(this.data.screenShotCanvas.toDataURL('image/webp'))
            this.updateProgressWidth()
          }
          collectorImage.src = res.tempImagePath
        }
      })
    } else {
      this.setData({ tipDisplay: 'block' })
      setTimeout(() => { this.setData({ tipDisplay: 'none', hide: false, }) }, 1000)
    }
  },
  takePhoto2: function() {
    const fileSystemManager = wx.getFileSystemManager()
    const appInstance = getApp()
    const blazeFaceModel = appInstance.globalData.blazeFaceModel
    this.data.cameraCtx.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log(res.tempImagePath)
        const collectorImage = this.data.collectorCanvas.createImage()
        collectorImage.onload = () => {
          this.data.collectorCanvasCtx.drawImage(collectorImage, 0, 0)
          const imageData = this.data.collectorCanvasCtx.getImageData(0, 0, this.data.collectorCanvasWidth, this.data.collectorCanvasHeight)
          console.log(imageData)
          blazeFaceModel.estimateFaces(imageData.data, { width: imageData.width, height: imageData.height }).then(predictions => {
            console.log(predictions)
          })
        }
        collectorImage.src = res.tempImagePath

        // const imageBase64 = fileSystemManager.readFileSync(res.tempImagePath, 'base64')
        // console.log(imageBase64)
        // const ab = wx.base64ToArrayBuffer(imageBase64)
        // console.log(ab)

        // blazeFaceModel.estimateFaces(frame.data, { width: frame.width, height: frame.height }).then(predictions => {
        //   console.log(predictions)
        // })
      }
    })
  },
  writeFile: function(buffer) {
    const fileSystemManager = wx.getFileSystemManager()
    const filePath = wx.env.USER_DATA_PATH + "/temp.jpg"
    fileSystemManager.writeFile({
      filePath: filePath,
      encoding: 'base64',
      data: buffer,
      success: (res) => {
        console.log(res)
        console.log(filePath)
        // this.setData({tempFile: filePath})
      },
      fail: function (err) {
        console.log("writeFile fail err:", err)
      },
    })
  },
  storePhoto: function (photo) {
    const photos = wx.getStorageSync('photos') || []
    photos.push(photo)
    wx.setStorageSync('photos', photos)
  },
  updateProgressWidth: function() {
    const photos = wx.getStorageSync('photos') || []
    this.setData({progressWidth: photos.length / 4 * 100})
  },
})